package site.model;


import site.model.dbdao.GenericDao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


public abstract class JpaGenericDao<T> implements GenericDao<T, Integer> {

    @PersistenceContext
    protected EntityManager em;

    private Class<T> type;

    public JpaGenericDao() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        type = (Class) pt.getActualTypeArguments()[0];
    }

    @Override
    public T create(final T t) {
        em.persist(t);
        return t;
    }

    @Override
    public void delete(final Integer id) {
        em.remove(em.getReference(type, id));
    }

    @Override
    public T find(final Integer id) {
        return (T) em.find(type, id);
    }

    @Override
    public T update(final T t) {
        return em.merge(t);
    }

    @Override
    public void refresh(T t) {
        em.refresh(t);
    }

    @Override
    public List<T> getAll() {
        return em.createQuery("select ent from " + type.getSimpleName() + " ent").getResultList();
    }
}